package com.beyondsoft.sabg.edu.util.dataanalysis;

import com.beyondsoft.sabg.edu.config.AnalysisConfig;
import com.beyondsoft.sabg.edu.model.dto.DataSourceConfigDto;
import com.beyondsoft.sabg.edu.service.dataanalysis.DataSourceService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 数据源初始化工具类
 * 应用启动时自动初始化数据源和同步表结构
 */
@Component
@Slf4j
public class DataSourceInitializer implements CommandLineRunner {

    @Autowired
    private DataSourceService dataSourceService;

    @Autowired
    private AnalysisConfig analysisConfig;

    @Override
    public void run(String... args) throws Exception {
        try {
            log.info("开始初始化析言数据源...");
            
            // 创建数据源配置
            DataSourceConfigDto config = new DataSourceConfigDto();
            config.setType(1); // MySQL
            config.setUrl(analysisConfig.getDatasourceUrl());
            config.setUserName(analysisConfig.getDatasourceUsername());
            config.setPassword(analysisConfig.getDatasourcePassword());
            
            // 创建数据源授权
            String authResult = dataSourceService.createDatasourceAuthorization(config);
            log.info("数据源授权结果：{}", authResult);
            
            // 同步数据表
            String syncResult = dataSourceService.syncRemoteTables(Arrays.asList(
                "analysis_employees",
                "analysis_departments", 
                "analysis_professional_titles",
                    "user_account"
            ));
            log.info("数据表同步结果：{}", syncResult);
            
            log.info("析言数据源初始化完成");
            
        } catch (Exception e) {
            log.warn("析言数据源初始化失败，可能已经初始化过：{}", e.getMessage());
        }
    }
} 